<?php
/*
 * @Author: your name
 * @Date: 2020-06-29 09:28:29
 * @LastEditTime: 2020-07-16 11:26:21
 * @LastEditors: 天羽落星辰
 * @Description: In User Settings Edit
 * @FilePath: \WWW\frx\application\api\controller\Index.php
 */ 

namespace app\api\controller;

use app\common\controller\Api;
use think\Validate;
use think\Db;

/**
 * 我的积分（活力值）
 */
class Score extends Api
{
    // protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 活力值转账to
     * @param string $mobile  收款手机号
     * @param string $money 金额
     * @param string $password 支付密码
     */ 
    public function score_to()
    {   
        $mobile = $this->request->request("mobile");
        $money = $this->request->request("money");
        $password = $this->request->request("password");
        $user = $this->auth->getuser();

        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机格式不正确'));
        }

        if(md5($password) != $user['secpwd']){
            $this->error('密码错误');
        }

        if($this->auth->mobile == $mobile){
            $this->error('不能转给自己');
        }
        
        if(empty($money) || $money == 0){
            $this->error('请输入活力值');
        }elseif($money > $this->auth->score){
            $this->error('余额不足');
        }

        // 启动事务
        Db::startTrans();
        try {
            db('user')->where('id',$this->auth->id)->lock(true)->count();
            $ouser = db('user')->field(true)->where('mobile',$mobile)->lock(true)->find();
            if(!$ouser){
                throw new \Exception("该手机号未注册");
            }
            $a1 = db('user')->where('id',$this->auth->id)->setDec('score', $money);
            $a2 = db('user')->where('id',$ouser['id'])->setInc('score', $money);
            $a3 = db('user_score_log')->insert([
                'uid' => $user['id'], 
                'uname' => $user['username'], 
                'money' => '-'.$money,
                'before' => $user['score'], 
                'after' => $user['score'] - $money, 
                'type' => '6', 
                'memo' => '活力值转出',
                'oid' => $ouser['id'], 
                'oname' => $ouser['username'], 
                'createtime' => time(),
                ]);
            $a4 = db('user_score_log')->insert([
                'uid' => $ouser['id'], 
                'uname' => $ouser['username'], 
                'money' => $money,
                'before' => $ouser['score'], 
                'after' => $ouser['score'] + $money, 
                'type' => '6', 
                'memo' => '活力值转入',
                'oid' => $user['id'], 
                'oname' => $user['username'], 
                'createtime' => time(),
                ]);
                if(!$a1 && !$a2 && !$a3 && !$a4){
                    throw new \Exception("转账失败");
                }
                // 提交事务
                Db::commit();  
        } catch (\Exception $th) {
            // 回滚事务
            Db::rollback();
            $this->error(($th->getMessage()));
        }
        $this->success('转账成功');

    }


    /**
     * 兑换usdt
     * @param string $money 金额
     */ 
    public function score_switch()
    {   

        $money = $this->request->request("money");
        $score_to_usdt = config('site.score_to_usdt');
        $user = $this->auth->getuser();


        if(empty($money) || $money == 0){
            $this->error('请输入活力值');
        }elseif($money > $this->auth->score){
            $this->error('余额不足');
        }elseif($money < 99){
            $this->error('单笔至少满99活力值');
        }
        // usdt兑换比例
        $usdt = $money / $score_to_usdt;

        // 启动事务
        Db::startTrans();        
        try {
            db('user')->where('id',$this->auth->id)->lock(true)->count();
            $a1 = db('user')->where('id',$this->auth->id)->inc('usdt',$usdt)->dec('score', $money)->update();
            $a2 = db('user_score_log')->insert([
                'uid' => $user['id'], 
                'uname' => $user['username'], 
                'money' => '-'.$money,
                'before' => $user['score'], 
                'after' => $user['score'] - $money, 
                'type' => 5, 
                'memo' => '活力值转出',
                'createtime' => time(),
                ]);
            $a3 = db('qianbao_sysetm_log')->insert([
                'uid' => $user['id'], 
                'uname' => $user['username'], 
                'money' => $usdt,
                'before' => $user['usdt'], 
                'after' => $user['usdt'] + $usdt, 
                'type' => 6, 
                'zt' => 1, 
                'memo' => '活力值兑换',
                'createtime' => time(),
                ]);
                if(!$a1 && !$a2 && !$a3){
                    throw new \Exception("转出失败");
                }
                // 提交事务
                Db::commit();  
        } catch (\Exception $th) {
            // 回滚事务
            Db::rollback();
            $this->error(($th->getMessage()));
        }
        $this->success('转出成功');



    }

    /**
     * 活力值明细记录
     * @param string $type  类型
     * @param string $limit  页数列表显示条数
     * @param string $paging 页数
     */ 
    public function score_log()
    {   
        $type = intval($this->request->request('type'));
        $limit = intval($this->request->request('limit'));
        $paging = intval($this->request->request('paging'));
        $limit = $limit ? $limit : 10;
        $paging = $paging ? 10 * $paging : 0;
        
        if($type == '5' || !$type){
            $id = 'uid';
            $type = '5';
        }elseif($type == '6'){
            $id = 'oid';
        }
        
        $data = db('user_score_log')->field('uname, money, createtime')->where($id,$this->auth->id)
        ->where('type',$type)
        ->limit($paging, $limit)
        ->order('id', 'desc')
        // ->fetchSql(true)
        ->select();

        if($data){
            foreach($data as &$v){
                $v['createtime'] = datetime($v['createtime']);
                $v['money'] = round($v['money'],2);
            }
        }

        $this->success('',$data);
    }

    
   
   
}
